package com.baidu;

import cn.hutool.core.util.StrUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        // 模拟从数据库或其他数据源获取学生列表
        List<Student> studentList = getStudentList();
        // 设置分页参数
        int pageSize = 5; // 每页显示的记录数
        int currentPage = 1; // 当前页数，默认为第一页
//        if (StrUtil.isNotEmpty(request.getAttribute("param1").toString())){
//            currentPage = (int) request.getAttribute("param1");
//        }
        String pageParam = request.getParameter("page");
        if (pageParam != null && !pageParam.isEmpty()) {
            currentPage = Integer.parseInt(pageParam);
        }

        // 计算分页的起始索引和结束索引
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, studentList.size());

        // 获取当前页的学生列表
        List<Student> currentPageStudents = studentList.subList(startIndex, endIndex);

        //会话request.getSession()

        // 将数据存储到request对象中，以便在JSP页面中使用 请求
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", (int) Math.ceil((double) studentList.size() / pageSize));
        request.setAttribute("studentList", currentPageStudents);

        // 转发到JSP页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
    }

    private List<Student> getStudentList() {
        List<Student> studentList = new ArrayList<>();
        try (Connection connection = JdcbConnection.requestConnection();
             Statement statement = connection.createStatement()){
            String sql = "select * from student";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                Student student = new Student(
                        Integer.parseInt(resultSet.getString("id")),
                        resultSet.getString("name"),
                        resultSet.getString("age")
                );
                studentList.add(student);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        // 此处可以连接数据库或其他数据源，这里只是模拟数据
        return studentList;

    }

}
